<?php

require_once("lib/autoload.php");

use phpcassa\ColumnFamily;
use phpcassa\Connection\ConnectionPool;
use cassandra\Compression;
use phpcassa\Schema\DataType\Int32Type;
	
class Database {
	
	private $rawConnection;
	private $connectionPool;
	
	public function __construct() {
		$this->pool = new ConnectionPool("pveb_12_1", array("192.168.71.33"));
		$this->raw = $this->pool->get();
	}
	
	public function executeQuery($query) {
		$cqlResult = $this->raw->client->execute_cql_query($query, Compression::NONE);

		if ($cqlResult->type == 1) { 
			$rows = array(); 

			foreach ($cqlResult->rows as $rowIndex => $cqlRow) { 
				$cols = array(); 
				foreach ($cqlRow->columns as $colIndex => $column) { 
					$cols[$column->name] = $column->value;
				} 
				$rows[] = $cols;
		     }   
			 return $rows; 
		 } else { 
			 return null;
		 }
	}
	
	public function parseIntegers($array, $keyName) {
		$result = $array;
		for ($i = 0; $i < count($result); $i++) {
			$row = $result[$i];
			$bla = unpack("H*",$row[$keyName]);
			$row[$keyName] = hexdec($bla["1"]);
			$result[$i] = $row;
		}
		
		return $result;
	}
	
	public function getMax($tableName, $keyName, $isInt) {
		$result = $this->executeQuery("SELECT " . $keyName . " FROM " . $tableName);
		if ($isInt) {
			$result = $this->parseIntegers($result, $keyName);
		}
		
		if (count($result) == 0) {
			return 0;
		}

		$max = $result[0][$keyName];
		for ($i = 1; $i < count($result); $i++) {
			if ($max < $result[$i][$keyName]) {
				$max = $result[$i][$keyName];
			}
		}
		
		return $max;
	}
	
	public function __destruct() {
		$this->pool->return_connection($this->raw);
		unset($this->raw);
	}
}

?>